package com.test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Set;

public class SocketServer {
	private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
	private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
	private static Selector selector;

	public void startSocketServer(int port) {
		try {
			ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			ServerSocket serverSocket = serverSocketChannel.socket();
			serverSocket.bind(new InetSocketAddress(port));
			selector = Selector.open();   
			serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

			while (true) { 
				selector.select();
				Set<SelectionKey> selectionKeys = selector.selectedKeys();
				for (SelectionKey key : selectionKeys) {
					handle(key);
				}
				selectionKeys.clear();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}


	private void handle(SelectionKey selectionKey) throws IOException {
		ServerSocketChannel serverSocketChannel = null;
		SocketChannel socketChannel = null;
		String requestMsg = "";
		int count = 0;
		if (selectionKey.isAcceptable()) {
			serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
			socketChannel = serverSocketChannel.accept();
			socketChannel.configureBlocking(false);
			socketChannel.register(selector, SelectionKey.OP_READ);
		} else if (selectionKey.isReadable()) {
			socketChannel = (SocketChannel) selectionKey.channel();
			rBuffer.clear();
			count = socketChannel.read(rBuffer);
			if (count > 0) {
				rBuffer.flip();
//                requestMsg = String.valueOf(cs.decode(rBuffer).array());
				//requestMsg = Arrays.toString(conver(rBuffer));
				requestMsg = ByteToHex(conver(rBuffer));
			}

			String responseMsg = "客户端消息:" + requestMsg;
			System.out.println(responseMsg);
			//传输是86 位的
			if (requestMsg.length() == 86) {
				String address = requestMsg.substring(0,20);
				System.err.println("地址位："+hexToAscii(address));
				read(requestMsg.substring(20));
				sBuffer = ByteBuffer.allocate("OK".getBytes("UTF-8").length);
				sBuffer.put("OK".getBytes("UTF-8"));
				sBuffer.flip();
			}else {
				sBuffer = ByteBuffer.allocate("OK".getBytes("UTF-8").length);
				sBuffer.put("OK".getBytes("UTF-8"));
				sBuffer.flip();
			}
			socketChannel.write(sBuffer);
//            socketChannel.close();
		}
	}

	public byte[] conver(ByteBuffer byteBuffer) {
		int len = byteBuffer.limit() - byteBuffer.position();
		byte[] bytes = new byte[len];

		if (byteBuffer.isReadOnly()) {
			return null;
		} else {
			byteBuffer.get(bytes);
		}
		return bytes;
	}
    
	public static String ByteToHex(byte[] bytes){
		StringBuilder result = new StringBuilder();
        for (byte aByte : bytes) {
            result.append(String.format("%02x", aByte));
        }
        return result.toString();

	}
	public static void main(String[] args) {
        SocketServer server = new SocketServer();
        server.startSocketServer(8088);
//		String requestMsg = "0f38363231383430353035303632303219035213031ee80100000501001001000000800101020102090000090000575a";
//		System.out.println(String.format("%s%s", requestMsg.substring(0, 32),"000000058100052a167a1d00a9b3")); 
	}

	/**
	 * 16进制转Ascii
	 * @param hexStr
	 * @return
	 */
	public static String hexToAscii(String hexStr) {
		StringBuilder output = new StringBuilder("");
		for (int i = 0; i < hexStr.length(); i += 2) {
			String str = hexStr.substring(i, i + 2);
			output.append((char) Integer.parseInt(str, 16));
		}
		return output.toString();
	}

	public void read(String requestMsg){

		String aa = requestMsg.substring(6,10);
		//System.out.println(aa);
		Integer x = Integer.parseInt(aa,16);
		System.err.println(String.format("%s:%s","空气温度",x));
//		BigDecimal bignum = new BigDecimal(x);
//		System.err.println(String.format("%s:%s","空气温度",bignum.divide(new BigDecimal(10)).setScale(1)));

		aa = requestMsg.substring(10,14);
		//System.out.println(aa);
		x = Integer.parseInt(aa,16);
//		bignum = new BigDecimal(x);
//		System.err.println(String.format("%s:%s","空气湿度",bignum.divide(new BigDecimal(10)).setScale(1)));
		System.err.println(String.format("%s:%s","空气湿度",x));

		aa = requestMsg.substring(22,26);
		//System.out.println(aa);
		x = Integer.parseInt(aa,16);
//		bignum = new BigDecimal(x);
//		System.err.println(String.format("%s:%s","氨气",bignum.divide(new BigDecimal(1000)).setScale(2)));
		System.err.println(String.format("%s:%s","氨气",x));


		aa = requestMsg.substring(26,30);
		//System.out.println(aa);
		x = Integer.parseInt(aa,16);
//		bignum = new BigDecimal(x);
//		System.err.println(String.format("%s:%s","硫化氢",bignum.divide(new BigDecimal(1000)).setScale(3)));
		System.err.println(String.format("%s:%s","硫化氢",x));
	};

}